package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.util.concurrent.AtomicDouble;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.AfterSalesWarranty;
import com.kws.merchant.domain.ContractTemplate;
import com.kws.merchant.domain.DeviceRemark;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.OperationRepertoryType;
import com.kws.merchant.domain.po.RemarkPage;
import com.kws.merchant.domain.vo.GoodsRemarkVo;
import com.kws.merchant.domain.vo.RemarkVo;
import com.kws.merchant.mapper.DeviceRemarkMapper;
import com.kws.merchant.service.DeviceRemarkService;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;
import javafx.util.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 设备评论表(DeviceRemark)表服务实现类
 *
 * @author yxy
 * @since 2024-10-22 15:26:03
 */
@Service("deviceRemarkService")
public class DeviceRemarkServiceImpl extends ServiceImpl<DeviceRemarkMapper, DeviceRemark> implements DeviceRemarkService {

    @Resource
    private DeviceRemarkMapper deviceRemarkMapper;
    @Value("${minio.ENDPOINT}")
    private String minioUrl;
    @Autowired
    private FileUtil fileUtil;


    /**
     * 根据设备id查询评论
     *
     * @param deviceId
     */
    @Override
    public List<DeviceRemark> getRemarkByDeviceId(Long deviceId) {
        List<DeviceRemark> list = this.list(Wrappers.<DeviceRemark>lambdaQuery().eq(DeviceRemark::getDeviceId, deviceId).eq(DeviceRemark::getPid, 0));
        list.forEach(x -> {
            List<DeviceRemark> treeList = getTreeList(x.getId());
            x.setChildrenList(treeList);
            List<String> remarkImgList  = new ArrayList<>();
            String remarkImg = x.getRemarkImg();
            if (StringUtils.isNotEmpty(remarkImg)) {
                String[] split = remarkImg.split("kws:");
                for (String s : split) {
                    remarkImgList.add(fileUtil.fixFileName()+s);
                }
            }
            x.setRemarkImgList(remarkImgList);
        });
        return list;
    }

    /**
     * 递归获取子节点数据
     *
     * @param id
     * @return
     */
    private List<DeviceRemark> getTreeList(Long id) {
        List<DeviceRemark> deviceRemarks = this.listByPid(id);
        deviceRemarks.forEach(x -> {
            List<DeviceRemark> treeList = getTreeList(x.getId());
            x.setChildrenList(treeList);
        });
        return deviceRemarks;
    }

    @Override
    public List<DeviceRemark> listByPid(Long pid) {
        return this.list(Wrappers.<DeviceRemark>lambdaQuery().eq(DeviceRemark::getPid, pid));
    }

    /**
     * 根据设备计算评分，规则为平均分
     *
     * @param deviceId
     * @return
     */
    @Override
    public GoodsRemarkVo scoreAvg(Long deviceId) {
        List<DeviceRemark> list = this.list(Wrappers.<DeviceRemark>lambdaQuery().eq(DeviceRemark::getDeviceId, deviceId).eq(DeviceRemark::getPid, 0));
        GoodsRemarkVo goodsRemarkVo = new GoodsRemarkVo();
        int count = list.size();
        AtomicDouble scoreCount = new AtomicDouble();
        AtomicDouble tag0 = new AtomicDouble();
        AtomicDouble tag1 = new AtomicDouble();
        list.forEach(x -> {
            Double score = x.getScore();
            Integer tag = x.getTag();
            switch (tag) {
                case 0:
                    tag0.addAndGet(1);
                    break;
                case 1:
                    tag1.addAndGet(1);
                    break;
            }
            scoreCount.addAndGet(score);

        });
        goodsRemarkVo.setGood(tag0.get());
        goodsRemarkVo.setOrdinary(tag1.get());
        goodsRemarkVo.setAllRemark(Double.valueOf(count));
        if (scoreCount.get() == 0 || count == 0) {
            goodsRemarkVo.setScore(0.0);
        }else{
            goodsRemarkVo.setScore(scoreCount.get() / count);
        }
        return goodsRemarkVo;
    }

    @Override
    public Page<DeviceRemark> pageList(RemarkPage remarkPage) {

        Integer pageSize = remarkPage.getPageSize();
        Integer totalPage = remarkPage.getTotalPage();
        String type = remarkPage.getType();//0设备 1商品服务
        Long goodsId = remarkPage.getGoodsId();
        //查询自己的签名和盖章
        String sql = " s.pid=0 and s.enable=1";
        if (!StringUtils.isEmpty(type)) {
            sql += " and s.remark_type=" + type;
        }
        if (goodsId != null) {
            sql += " and s.device_id=" + goodsId;
        }
        int total = deviceRemarkMapper.countToTal(sql);
        int sizeNum = (pageSize - 1) * totalPage;//计算分页
        //查询评论数据
        List<DeviceRemark> records = deviceRemarkMapper.getRecords(sql, sizeNum, totalPage);
        records.forEach(x -> {
            List<DeviceRemark> treeList = getTreeList(x.getId());
            x.setChildrenList(treeList);
            List<String> remarkImgList = x.getRemarkImgList();
            String remarkImg = x.getRemarkImg();
            if (StringUtils.isNotEmpty(remarkImg)) {
                Arrays.stream(remarkImg.split(",")).forEach(y -> {
                    remarkImgList.add(FileUtil.fixFileName() + y);
                });
            }
        });
        Page<DeviceRemark> page = new Page<>();
        page.setRecords(records);
        page.setTotal(total);
        page.setCurrent(pageSize);
        page.setPages((total + totalPage - 1) / totalPage);
        page.setSize(totalPage);
        return page;
    }
}
